﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Zyg.Utility.Helper;
using Zyg.SSO.Core.Business;

namespace Zyg.SSO.Web.Admin.App
{
    public partial class AppDetail : Zyg.SSO.Web.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!base.Account.HavePermission(Permission.AppManage))
                {
                    throw new Exception("你无权查看此页面");
                }
                bool parseSucceed;

                Guid id = Request.QueryString["id"].ToGuid(out parseSucceed);

                if (parseSucceed)
                {
                    BindData(id);
                }
                else
                {
                    throw new Exception("对不起，你所访问的页面不存在");
                }
            }
        }

        protected void BindData(Guid id)
        {
            Zyg.SSO.Core.Business.App app = Zyg.SSO.Core.Business.App.Load(id);

            if (app == null)
            {
                throw new Exception("对不起，你所访问的页面不存在");
            }

            AppSSOId.Text = app.Id.ToString();
            AppIP.Text = app.IP;
            AppName.Text = app.Name;
            AppPort.Text = app.Port.ToString();
            AppUrl.Text = app.Url;
            AppLoginFileAddress.Text = app.ToString();

            if (!string.IsNullOrEmpty(app.PictureAddress))
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(Server.MapPath(app.PictureAddress));

                if (fileInfo.Exists)
                {
                    AppPic.ImageUrl = app.PictureAddress;
                }
                else
                {
                    AppPic.ImageUrl = "~/Content/Account/no_head.gif";
                }
            }
            else
            {
                AppPic.ImageUrl = "~/Content/Account/no_head.gif";
            }

            AppId.Value = app.Id.ToString();
        }

        protected void BtnDelete_Click(object sender, EventArgs e)
        {
            bool parseSucceed;
            Guid id = Request.QueryString["id"].ToGuid(out parseSucceed);
            Zyg.SSO.Core.Business.App app = Zyg.SSO.Core.Business.App.Load(id);

            if (app == null)
            {
                WriteBackScript("alert('删除成功');window.location.href='AppList.aspx';");
            }

            if (app.Accounts.Count > 0)
            {
                WriteBackScript("alert('当前AP已拥有用户,不能删除!');");
            }
            else
            {
                app.DeleteOnSave();
                app.Save();

                WriteBackScript("alert('删除成功');window.location.href='AppList.aspx';");
            }
        }
    }
}
